﻿namespace Digitalmes.Application.Sys.Menus.Commands;

/// <summary>
/// 删除菜单命令。
/// </summary>
public record DeleteMenuCommand(long Id) : IRequest<IResult<bool>>;

internal sealed class DeleteMenuCommandHandler(IRepository<SysMenu> repo) : IRequestHandler<DeleteMenuCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
    {
        List<long> menuIds = [request.Id];

        // 查找此菜单的子项，且一并删除
        await GetChildrenAsync([.. menuIds]);

        var ok = await repo.DeleteByIdAsync([.. menuIds], cancellationToken);
        return Result.From(ok);

        async Task GetChildrenAsync(long[] ids)
        {
            var children = await repo.GetListAsync(s => ids.Contains(s.ParentId), cancellationToken);
            var ids2 = children.Select(s => s.Id).ToArray();
            if (ids2.Length > 0)
            {
                menuIds.AddRange(ids2);
                await GetChildrenAsync(ids);
            }
        }
    }
}
